<template>
  <!-- <el-button plain @click="open1"> Top Right </el-button> -->
  <!-- <router-view v-if="isRouterAlive" /> -->
  <test />
</template>

<script>
import Test from "./components/test";
import { ref, provide, nextTick, h, onUnmounted } from "vue";
import { ElNotification } from "element-plus";
export default {
  name: "App",
  components: { Test },
  setup() {
    const notifyMsg = (msg) => {
      ElNotification({
        title: "--MESSAGE--",
        message: h("i", { style: "color: teal" }, msg),
        type: "success",
        showClose: false,
        // position: "bottom-left",
      });
    };
    provide("notifyMsg", notifyMsg);
    // webSocket origin
    var websocket = null;
    // 连接WebSocket
    const createWebSocket = (userId) => {
      if ("WebSocket" in window) {
        var protocol =
          window.location.protocol === "http:" ? "ws://" : "wss://";
        websocket = new WebSocket(protocol + `localhost:8080/ws/${userId}`);
      } else {
        alert("该浏览器不支持WebSocket");
      }
      websocket.onopen = function (event) {
        // heartCheck.reset().start();
        console.log("建立 WebSocket 连接");
      };

      websocket.onclose = function (event) {
        console.log("断开WebSocket连接");
      };

      websocket.onmessage = function (event) {
        notifyMsg(event.data);
      };

      websocket.onerror = function (event) {
        console.log("websocket通信发生错误");
      };

      provide("websocket", websocket);
      /*   window.onbeforeunload = function (event: any) {
      websocket.close();
    }; */
    };
    provide("createWebSocket", createWebSocket);
    onUnmounted(() => {
      websocket.close();
    });
  },

  /*
    const isRouterAlive = ref(true);
    function reload() {
      isRouterAlive.value = false;
      nextTick(function () {
        isRouterAlive.value = true;
      });
    }
    provide("reload", reload);
    return {
      isRouterAlive,
    };
  }, */
};
</script>

